import redis
import random
import qrcode
import uuid
import os

import tornado.web
from tornado.routing import URLSpec
from tornado.web import RequestHandler


BASE_DIR = os.path.dirname(os.path.abspath(__file__))

pool = redis.ConnectionPool(host='localhost', port=6379, db=0,
                            decode_responses=True)
r = redis.Redis(connection_pool=pool)

host = 'http://172.16.49.14:8880'
host = 'http://2633d423.ngrok.io'

class MainHandler(RequestHandler):
    def get(self, cid):
        topic = ''
        if cid == '':
            uid = self.get_cookie('uid')
            if uid and r.exists(uid):
                pass
            else:
                uid = random.randint(1, 100)
                self.set_cookie('uid', '%d' % uid)

                topic = str(uuid.uuid4()).replace('-', '')
                r.setnx(uid, topic)

            self.render("c.html", topic=topic, uid=uid)

        else:
            if r.exists(cid):
                topic = r.get(cid)
                r.delete(cid)
                self.render("m.html", topic=topic, uid='B%s' % cid)

            else:
                self.render("c.html", topic=topic, uid=cid)


class QRHandler(RequestHandler):
    def get(self):
        uid = self.get_cookie('uid')

        img = qrcode.make('%s/%s' % (host, uid))
        img.save(self)


if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/([0-9]*)", MainHandler),
        URLSpec(r"/qr", QRHandler, name='qr')
    ], **{
        'debug': True,
        'template_path': os.path.join(BASE_DIR, 'templates'),
        'static_path': os.path.join(BASE_DIR, 'statics'),

    })
    application.listen(8880)
    tornado.ioloop.IOLoop.current().start()